package server.autorization.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controllers.Autoservice;
import autoservice.api.controller.IAutoservice;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IAutoservice autoservice = Autoservice.getInstance();
	private static final String SUCCESSFUL_AUTORIZATION = "WELCOME, ";
	private static final String UNSUCCESSFUL_AUTORIZATION = "Wrong login or password";
	private static final String LOGIN = "login";
	private static final String PASSWORD = "password";
	private static final String ANSWER = "answer";
	private static final String MAIN_PAGE = "/autorizationpages/MainPage.jsp";
	private static final String LOGIN_PAGE = "/autorizationpages/LoginPage.html";
	private static final String AUTORIZATION = "autorization";
	private static final String USER = "user";

	public LoginServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter(LOGIN);
		String password = request.getParameter(PASSWORD);
		String answer = autoservice.getAutorization(login, password);

		if (answer != null) {
			request.setAttribute(ANSWER, SUCCESSFUL_AUTORIZATION + answer);
			autoservice.setOperation(login, AUTORIZATION);
			request.getSession().setAttribute(USER, login);
			request.getRequestDispatcher(MAIN_PAGE).forward(request, response);
		} else {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					LOGIN_PAGE);
			PrintWriter out = response.getWriter();
			out.println(UNSUCCESSFUL_AUTORIZATION);
			rd.include(request, response);
		}

	}

}
